<template>
  <view class="content">
    <view class="web">
      <scroll-view :scroll-top="scrollTop" :scroll-with-animation="true" :scroll-y="true">
        <view v-for="item, i in msgList" :key="i">
          <view class="itemI" v-if="item.botContent">
            <view class="left">
              <image src="https://digital.essc.top/dist/zjl_icon/chengjiao.png" mode="scaleToFill" />
            </view>
            <view class="right">
              <view class="title">{{ item.time }}</view>
              <view class="cont">{{ item.botContent }}</view>
            </view>
          </view>
          <view class="itemII" v-if="item.userContent">
            <view class="left">
              <image src="https://digital.essc.top/dist/zjl_icon/chengjiao.png" mode="scaleToFill" />
            </view>
            <view class="right">
              <view class="title">{{ item.time }}</view>
              <view class="cont">{{ item.userContent }}</view>

            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="button">
      <uni-easyinput class="uni-mt-5" :styles="styles" trim="all" v-model="chatMsg" placeholder="请输入内容"></uni-easyinput>
      <button @click="handleSend()">发送</button>
    </view>
  </view>
</template>

<script>
const app = getApp()
// const  app.globalData.
import {
  GroupServesHistory
} from '@/api/group.js'
import {
  GoodsFileAdd
} from '@/api/global.js'
import times from "@/static/js/utils.js";

export default {
  onLoad(options) {
    // 存储页面跳转所需的参数
    this.options = options;
    this.connectSocketInit();
    this.getHistoryList({
      Group_ID: uni.getStorageSync("use"),
      User_Type: "custom",
      Enterprise_Info_SerialNumber: options.Enterprise_Info_SerialNumber,
    });
  },
  onReady() {
    this.Enterprise_Info_SerialNumber = this.options.Enterprise_Info_SerialNumber;
    // 在页面加载完成后设置导航栏标题
    uni.setNavigationBarTitle({
      title: this.options.name
    });
  },
  data() {
    return {
      options: {},
      chatMsg: "",
      option: "",
      scrollTop: 0,
      ThemeColors: app.globalData.ThemeColors,
      Domain_IMG: app.globalData.Domain_IMG,
      Domain_Socket: app.globalData.Domain_Socket,
      UserId: [],
      msgList: [],
      socketTask: null,
      is_open_socket: false, // 确保websocket是打开状态
      hearBeatInterval: null, //心跳
      usePhone: uni.getStorageSync('use'),
      Enterprise_Info_SerialNumber: 0,
      styles: {
        borderColor: '#fff'
      }

    };
  },

  methods: {
    connectSocketInit() {
      // 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
      this.socketTask = uni.connectSocket({
        url: app.globalData.Domain_Socket + "/websocket?userId=Group" + this.usePhone,
        success(data) {
          console.log("websocket连接成功");
        },
      });
      // // 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
      this.socketTask.onOpen((res) => {
        console.log("WebSocket连接正常打开中...！");
        this.is_open_socket = true;
        // // 注：只有连接正常打开中 ，才能正常成功发送消息
        this.hearBeatInterval = setInterval(() => {
          this.socketTask.send({
            data: "ping",
          });
        }, 30000);
        // 注：只有连接正常打开中 ，才能正常收到消息
        this.socketTask.onMessage((res) => {
          console.log(JSON.parse(res.data));
          let time = JSON.parse(res.data).data.time;
          let message = JSON.parse(res.data).data.message;
          this.msgList.push({
            botContent: message,
            userContent: "",
            time,
          });
        });
      });
      // // 这里仅是事件监听【如果socket关闭了会执行】
      this.socketTask.onClose(() => {
        this.is_open_socket = false;
        clearInterval(this.hearBeatInterval);
        console.log("已经被关闭了");
      });
    },
    handleSend() {
      //如果消息不为空
      if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
        let time = times.nowtime();
        let obj = {
          botContent: "",
          userContent: this.chatMsg,
          time: times.nowtime(),
        };
        this.msgList.push(obj);
        if (this.is_open_socket && this.chatMsg != "") {
          console.log(1);
          this.socketTask.send({
            data: JSON.stringify({
              time,
              message: this.chatMsg,
              userId: this.Enterprise_Info_SerialNumber,
            }),
            async success() {
              console.log("消息发送成功");
            },
          });
          let data = {
            Data: JSON.stringify({
              group_serves_news: [
                {
                  Group_Serves_SerialNumber: "",
                  Group_User_Number: uni.getStorageSync("use"),
                  Group_Serves_ID: this.Enterprise_Info_SerialNumber,
                  Group_Message: this.chatMsg,
                  Group_Message_Time: times.nowtime(),
                  Group_Message_Type: "",
                  Enterprise_Info_SerialNumber: this.Enterprise_Info_SerialNumber,
                  Row_Status: "0",
                },
              ],
            }),
          };
          this.MessagesFileAdd(data);
        }
        this.chatMsg = "";
      } else {
        uni.showToast({
          title: "不能发空消息哦",
          icon: "error",
        });
      }
    },
    //
    async MessagesFileAdd(data) {
      const res = await GoodsFileAdd({
        data,
      });
      if (res.redirect && res.redirect == "REDIRECT" || res.REDIRECT == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        console.log(res);
      }
    },
    //获取消息历史记录
    async getHistoryList(data) {
      const res = await GroupServesHistory({
        data,
      });
      if (res.redirect && res.redirect == "REDIRECT") {
        console.log(res.redirect);
      } else if (res.Status == "success") {
        console.log(res);
        this.msgList = res.Data;
        this.ScrollBottom();
      }
    },
    //滚动到消息底部
    ScrollBottom(i = 0) {
      console.log("滚动了");
      // this.scrollTop = (124-48)*i
      this.$nextTick(() => {
        this.scrollTop = 10000 + i * 10;
      });
    },
    closeSocket() {
      if (this.is_open_socket) {
        this.socketTask.close()
        clearInterval(this.hearBeatInterval)
      }
    },
  },
  onUnload() {
    this.closeSocket()
  }
}
</script>

<style lang="scss">
.content {
  width: 100%;
  background: #f5f5ff;
  height: calc(100vh);

  .web {
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    // margin: 0 0 186rpx 0;
    height: calc(100vh);

    .itemI {
      width: 100%;
      // height: 80rpx;
      display: flex;

      .left {
        width: 100rpx;
        height: 100rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .right {
        margin: 0 0 0 20rpx;

        .title {
          font-size: 24rpx;
        }

        .cont {
          margin: 20rpx 0 0 0;
          background: #fff;
          border-radius: 20rpx;
          height: 80rpx;
          text-align: center;
          line-height: 80rpx;
        }

      }
    }

    .itemII {
      // height: 80rpx;
      width: 100%;
      display: flex;
      justify-content: flex-start;
      flex-direction: row-reverse;
      margin: 10rpx 0 0 0;

      .left {
        width: 100rpx;
        height: 100rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .right {
        margin: 0 20rpx 0 0;

        .title {
          font-size: 24rpx;
        }

        .cont {
          margin: 20rpx 0 0 0;
          background: #fff;
          border-radius: 20rpx;
          height: 80rpx;
          text-align: center;
          line-height: 80rpx;
        }

      }
    }
  }

  .button {
    // height: 186rpx;
    // padding: 20rpx 30rpx;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: fixed;
    bottom: -1px;
    left: 0;
    width: 100%;
    box-sizing: border-box;

    button {
      font-size: 32rpx;
      text-align: center;
      line-height: 32rpx;
      display: block;
      padding: 24rpx 0;
      box-sizing: border-box;
      background: #28a745;
      color: #fff;
      width: 100rpx;
      // height: 100%;
    }

    .cal {
      background-color: #f39147;
    }

    .text_ca {
      width: 200rpx;
      height: 40px;
      margin: 0;
      border: none;
      // padding: 10rpx 0;
    }
  }
}
</style>